package clientgui;

import java.util.ArrayList;
import java.util.Collections;

import client.Client;
import exchange.Parser;
import message.Order;

public class ValidatorGUI {

	public String validate(String symbol, String qty, String Price,
			boolean isMarket) {

		return "ok";
	}

	public static Order doNewOrder(String clientId, String orderId,
			String symbol, String operationString, String priceString,
			String qtyString) throws Exception {
		double price = 0;
		int operation = 0;
		int qty = 0;
		try {
			orderId = Client.getOrderId();
			operation = ("BUY".equals(operationString)) ? 1 : 2;
			price = Double.parseDouble(priceString);
			qty = Integer.parseInt(qtyString);
		} catch (NumberFormatException e) {
			throw (new Exception("wrong numbers"));
		}
		return new Order(clientId, orderId, symbol, operation, price, qty);
	}

	public static String acceptER(String message) {
		Parser parser = new Parser();
		String messageType = parser.takeValue(message, "35");
		String text;
		switch (messageType) {
		case "A": // logon
			return "Logon successfull";
		case "5": // logout
			text = parser.takeValue(message, "58");
			return "Logon failed: " + text;
		case "8": // new order
			String orderId = parser.takeValue(message, "11");
			Order o = Client.getOrderById(orderId);
			int status = Integer.parseInt(parser.takeValue(message, "39"));
			o.setStatus(status);
			if (status == 0) {
				return "Order " + orderId + " accepted";
			}

			if (status == 1 || status == 2) {
				int cumQty = Integer.parseInt(parser.takeValue(message, "14"));
				int leavesQty = Integer.parseInt(parser.takeValue(message,
						"151"));
				o.setLeavesQty(leavesQty);
				o.setCumQty(cumQty);
				return "Order " + orderId + " (part)filled";
			}
			if (status == 8) {
				text = parser.takeValue(message, "58");
				return "Order " + orderId + " rejected: " + text;
			}
			return "ER" + orderId;
		default:
			return "Unknown message received";
		}
	}

	public static void refresh() {
		Client.orders.keySet();
		StringBuilder row = new StringBuilder();
		ArrayList<String> keys = new ArrayList<String>(Client.orders.keySet());
		Collections.sort(keys);
		Collections.reverse(keys);
		for (String key : keys) {
			row.append(Client.orders.get(key));
			row.append("\n");
		}
		Client.mainwindow.textPane.setText(row.toString());

	}

	public static void updateTip(String tip) {
		Client.mainwindow.lblHelp.setText(tip);
	}

}
